<template>
  <view class="maintenance-order-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="运维工单" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 工单状态筛选 -->
            <view class="filter-item">
              <text class="filter-label">工单状态：</text>
              <up-tabs :list="statusList" :scrollable="false" @change="handleStatusChange"
                :current="currentStatus"></up-tabs>
            </view>

            <!-- 时间筛选 -->
            <view class="filter-item">
              <text class="filter-label">时间筛选：</text>
              <up-tabs :list="timeRangeList" :scrollable="true" @change="handleTimeRangeChange"
                :current="currentTimeRange"></up-tabs>
            </view>

            <!-- 自定义时间选择 -->
            <view v-if="currentTimeRange === 5" class="custom-time-section">
              <view class="time-picker-row">
                <view class="time-picker">
                  <text class="title">自定义时间</text>
                  <uni-datetime-picker type="daterange" :border="false" v-model="customTimeRange.dateRange"
                    @change="handleDateRangeChange"></uni-datetime-picker>
                </view>
              </view>
            </view>

            <!-- 泊位号搜索 -->
            <view class="filter-item">
              <up-search v-model="searchForm.berthNumber" :clearabled="true" :showAction="true" placeholder="请输入泊位号"
                @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="maintenance-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              工单编号：<text class="number">{{ item.orderNo }}</text>
            </view>
            <view class="status-badge" :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">负责人：</text>
                <text class="value">{{ item.assigneeName || '未指派' }}</text>
              </view>
              <view class="item">
                <text class="label">异常类型：</text>
                <text class="value exception-type" :class="getExceptionTypeClass(item.exceptionType)">{{
                  item.exceptionType
                  }}</text>
              </view>
              <view class="item">
                <text class="label">泊位号：</text>
                <text class="value">{{ item.berthNumber }}</text>
              </view>
              <view class="item">
                <text class="label">设备编号：</text>
                <text class="value">{{ item.deviceSN }}</text>
              </view>
              <view class="item">
                <text class="label">创建时间：</text>
                <text class="value">{{ item.createTime }}</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="info" text="查看详情" class="custom-style" @click="handleViewDetail(item)"></up-button>
                <up-button v-if="item.status === 'pending'" type="primary" text="指派任务" class="custom-style"
                  @click="handleAssignTask(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 指派任务弹窗 -->
    <up-popup v-model:show="showAssignModal" mode="center" :round="10">
      <view class="assign-modal">
        <view class="modal-header">
          <text class="modal-title">指派任务</text>
          <up-icon name="close" @click="closeAssignModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">选择巡检员：</text>
            <up-search v-model="assignForm.inspectorKeyword" placeholder="搜索巡检员" @search="searchInspector"></up-search>
            <view class="inspector-list">
              <view class="inspector-item" v-for="inspector in filteredInspectors" :key="inspector.id"
                @click="selectInspector(inspector)"
                :class="{ active: assignForm.selectedInspector?.id === inspector.id }">
                <text class="inspector-name">{{ inspector.name }}</text>
                <text class="inspector-phone">{{ inspector.phone }}</text>
              </view>
            </view>
          </view>
          <view class="form-item">
            <text class="form-label">备注：</text>
            <up-textarea v-model="assignForm.remark" placeholder="请输入备注信息" maxlength="200"></up-textarea>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="info" @click="closeAssignModal">取消</up-button>
          <up-button type="primary" @click="confirmAssign">确认指派</up-button>
        </view>
      </view>
    </up-popup>

    <!-- 查看详情弹窗 -->
    <up-popup v-model:show="showDetailModal" mode="center" :round="10">
      <view class="detail-modal">
        <view class="modal-header">
          <text class="modal-title">工单详情</text>
          <up-icon name="close" @click="closeDetailModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="detail-item">
            <text class="detail-label">工单编号：</text>
            <text class="detail-value">{{ currentDetail.orderNo }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">泊位编号：</text>
            <text class="detail-value">{{ currentDetail.berthNumber }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">设备编号：</text>
            <text class="detail-value">{{ currentDetail.deviceSN }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">工单类型：</text>
            <text class="detail-value">运维工单</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">停车场：</text>
            <text class="detail-value">{{ currentDetail.parkingLot }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">异常类型：</text>
            <text class="detail-value">{{ currentDetail.exceptionType }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">创建时间：</text>
            <text class="detail-value">{{ currentDetail.createTime }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">负责人：</text>
            <text class="detail-value">{{ currentDetail.assigneeName || '未指派' }}</text>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="primary" @click="closeDetailModal">关闭</up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import { getMaintenanceJobList } from '@/api';

// 工单状态选项
const statusList = [
  { name: '全部' },
  { name: '待指派' },
  { name: '待处理' },
  { name: '已处理' },
];
const currentStatus = ref(0);

// 时间筛选选项
const timeRangeList = [
  { name: '近7天' },
  { name: '近1个月' },
  { name: '近3个月' },
  { name: '近半年' },
  { name: '近1年' },
  { name: '自定义' },
];
const currentTimeRange = ref(0);

// 自定义时间范围
const customTimeRange = reactive({
  startTime: '',
  endTime: '',
  dateRange: []
});

// 搜索表单数据
const searchForm = reactive({
  berthNumber: '',
});

// z-paging 组件引用
const paging = ref(null);

// 当前显示的列表数据
const currentList = ref([]);

// 指派任务相关
const showAssignModal = ref(false);
const assignForm = reactive({
  inspectorKeyword: '',
  selectedInspector: null,
  remark: ''
});

// 巡检员列表
const inspectorList = ref([
  { id: 1, name: '张三', phone: '13800138001' },
  { id: 2, name: '李四', phone: '13800138002' },
  { id: 3, name: '王五', phone: '13800138003' },
  { id: 4, name: '赵六', phone: '13800138004' },
]);

// 过滤后的巡检员列表
const filteredInspectors = computed(() => {
  if (!assignForm.inspectorKeyword) {
    return inspectorList.value;
  }
  return inspectorList.value.filter(inspector =>
    inspector.name.includes(assignForm.inspectorKeyword) ||
    inspector.phone.includes(assignForm.inspectorKeyword)
  );
});

// 查看详情相关
const showDetailModal = ref(false);
const currentDetail = ref({});

// 工单状态切换事件
const handleStatusChange = (e) => {
  currentStatus.value = e.index;
  if (paging.value) {
    paging.value.reload();
  }
};

// 时间筛选切换事件
const handleTimeRangeChange = (e) => {
  currentTimeRange.value = e.index;
  // 如果不是自定义时间范围，则清空自定义时间
  if (currentTimeRange.value !== 5) {
    customTimeRange.dateRange = [];
    customTimeRange.startTime = '';
    customTimeRange.endTime = '';
  }
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理日期范围变化
const handleDateRangeChange = (e) => {
  if (Array.isArray(e) && e.length === 2) {
    customTimeRange.startTime = e[0];
    customTimeRange.endTime = e[1];
    if (paging.value) {
      paging.value.reload();
    }
  }
};

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  searchForm.berthNumber = '';
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.navigateTo({
    url: '/pages/work-order/index'
  });
};

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    'pending': 'status-pending',
    'processing': 'status-processing',
    'completed': 'status-completed'
  };
  return statusMap[status] || '';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待指派',
    'processing': '待处理',
    'completed': '已处理'
  };
  return statusMap[status] || status;
};

// 获取异常类型样式类
const getExceptionTypeClass = (type) => {
  const typeMap = {
    '设备离线': 'type-offline',
    '低电量预警': 'type-low-battery',
    '秒图异常': 'type-image-error',
    '设备时间异常': 'type-time-error',
    '设备损坏': 'type-damage'
  };
  return typeMap[type] || '';
};

// 指派任务
const handleAssignTask = (item) => {
  assignForm.selectedInspector = null;
  assignForm.inspectorKeyword = '';
  assignForm.remark = '';
  showAssignModal.value = true;
};

// 搜索巡检员
const searchInspector = () => {
  // 搜索逻辑已在computed中实现
};

// 选择巡检员
const selectInspector = (inspector) => {
  assignForm.selectedInspector = inspector;
};

// 确认指派
const confirmAssign = () => {
  if (!assignForm.selectedInspector) {
    uni.showToast({
      title: '请选择巡检员',
      icon: 'none'
    });
    return;
  }

  // 这里应该调用API进行指派
  uni.showToast({
    title: '指派成功',
    icon: 'success'
  });

  closeAssignModal();
  if (paging.value) {
    paging.value.reload();
  }
};

// 关闭指派弹窗
const closeAssignModal = () => {
  showAssignModal.value = false;
};

// 查看详情
const handleViewDetail = (item) => {
  currentDetail.value = item;
  showDetailModal.value = true;
};

// 关闭详情弹窗
const closeDetailModal = () => {
  showDetailModal.value = false;
};

// 获取运维工单列表数据
const queryList = async (pageNo, pageSize) => {
  // 构建API请求参数
  const params = {
    pageNum: pageNo,
    pageSize: pageSize,
    status: currentStatus.value === 0 ? -1 : currentStatus.value - 1, // 转换状态：0全部->-1, 1待指派->0, 2待处理->1, 3已处理->2
    keyword: searchForm.berthNumber || '', // 泊位关键字
    dateType: currentTimeRange.value === 5 ? -1 : currentTimeRange.value // 如果是自定义时间，设置为-1
  };

  // 如果是自定义时间，添加时间参数
  if (currentTimeRange.value === 5 && customTimeRange.dateRange && customTimeRange.dateRange.length === 2) {
    params.startDate = customTimeRange.dateRange[0];
    params.endDate = customTimeRange.dateRange[1];
  }

  await fetchList(params);
};

// 调用API获取数据
const fetchList = async (params) => {
  try {
    const res = await getMaintenanceJobList(params);

    if (res.success) {
      // 转换API返回的数据格式为页面所需格式
      const records = (res.data.records || []).map(item => {
        // 转换工单状态
        let status = 'pending';
        if (item.zpType === '1') {
          status = 'processing'; // 已指派，待处理
        } else if (params.status === 2) {
          status = 'completed'; // 已处理
        }

        // 转换异常类型
        const errorTypeMap = {
          '0': '设备离线',
          '1': '低电量预警',
          '2': '秒图异常',
          '3': '设备时间异常',
          '4': '设备损坏'
        };

        return {
          orderNo: item.bizCode,
          berthNumber: item.berthNo,
          deviceSN: item.deviceSn,
          exceptionType: item.errorTypeName || errorTypeMap[item.errorType] || '未知异常',
          status: status,
          assigneeName: item.inspectorName || null,
          assigneeId: item.inspectorId || null,
          createTime: item.createTime,
          parkingLot: item.veName || '',
          veId: item.veId
        };
      });

      paging.value.complete(records);
    } else {
      uni.showToast({
        title: res.msg || '获取数据失败',
        icon: 'none'
      });
      paging.value.complete(false);
    }
  } catch (error) {
    console.error('获取运维工单列表失败:', error);
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    });
    paging.value.complete(false);
  }
};

// 页面挂载时获取数据
onMounted(() => {
  if (paging.value) {
    paging.value.reload();
  }
});
</script>

<style scoped lang="scss">
.maintenance-list {
  padding: 20px;
}

.filter-section {
  .filter-item {
    margin-bottom: 20rpx;

    .filter-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
      display: block;
    }
  }

  .custom-time-section {
    margin-top: 20rpx;

    .time-picker-row {
      display: flex;
      align-items: center;

      .time-picker {
        width: 100%;
        display: flex;
        align-items: center;
        background-color: #f8f8f8;
        padding: 10rpx 20rpx;
        border-radius: 8rpx;
        margin-bottom: 20rpx;

        .title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-right: 20rpx;
        }
      }

      .time-separator {
        font-size: 28rpx;
        color: #666;
        margin: 0 10rpx;
      }
    }
  }
}

// 列表卡片样式
.list-item-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .card-header {
    padding: 24rpx 30rpx 16rpx;
    border-bottom: 1px solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;

      .number {
        color: #1890ff;
      }
    }

    .status-badge {
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      font-size: 22rpx;

      &.status-pending {
        background: #fff2e8;
        color: #fa8c16;
      }

      &.status-processing {
        background: #e6f7ff;
        color: #1890ff;
      }

      &.status-completed {
        background: #f6ffed;
        color: #52c41a;
      }
    }
  }

  .card-content-box {
    padding: 20rpx 30rpx;

    .content {
      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          font-size: 26rpx;
          color: #666;
          flex-shrink: 0;
        }

        .value {
          font-size: 26rpx;
          color: #333;
          text-align: right;

          &.exception-type {
            font-weight: bold;

            &.type-offline {
              color: #ff4d4f;
            }

            &.type-low-battery {
              color: #fa8c16;
            }

            &.type-image-error {
              color: #722ed1;
            }

            &.type-time-error {
              color: #1890ff;
            }

            &.type-damage {
              color: #f5222d;
            }
          }
        }
      }
    }

    .card-footer {
      margin-top: 24rpx;
      padding-top: 20rpx;
      border-top: 1px solid #f5f5f5;

      .operate {
        display: flex;
        justify-content: flex-end;
        gap: 20rpx;

        .custom-style {
          border-radius: 8rpx;
          font-size: 24rpx;
        }
      }
    }
  }
}

// 弹窗样式
.assign-modal,
.detail-modal {
  width: 600rpx;
  background: #fff;
  border-radius: 20rpx;

  .modal-header {
    padding: 30rpx;
    border-bottom: 1px solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .modal-content {
    padding: 30rpx;
    max-height: 600rpx;
    overflow-y: auto;

    .form-item,
    .detail-item {
      margin-bottom: 30rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .form-label,
      .detail-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
        display: block;
      }

      .detail-value {
        font-size: 28rpx;
        color: #666;
      }
    }

    .inspector-list {
      max-height: 300rpx;
      overflow-y: auto;
      border: 1px solid #f0f0f0;
      border-radius: 8rpx;
      margin-top: 10rpx;

      .inspector-item {
        padding: 20rpx;
        border-bottom: 1px solid #f5f5f5;
        display: flex;
        justify-content: space-between;
        align-items: center;

        &:last-child {
          border-bottom: none;
        }

        &.active {
          background: #e6f7ff;
          color: #1890ff;
        }

        .inspector-name {
          font-size: 28rpx;
          font-weight: bold;
        }

        .inspector-phone {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }

  .modal-footer {
    padding: 30rpx;
    border-top: 1px solid #f5f5f5;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
  }
}
</style>